package com.eii.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.eii.common.constant.BusinessTypeConstants;
import com.eii.common.constant.UserConstants;
import com.eii.common.web.controller.BaseController;
import com.eii.common.web.domain.Result;
import com.eii.common.web.page.PageResult;
import com.eii.excel.util.ExcelUtils;
import com.eii.log.annotation.AuditLog;
import com.eii.oauth2.common.annotation.RequiresPermissions;
import com.eii.oauth2.common.util.SecurityUtils;
import com.eii.system.api.domain.SysRole;
import com.eii.system.api.domain.SysUser;
import com.eii.system.controller.vo.SysRoleExcel;
import com.eii.system.domain.SysUserRole;
import com.eii.system.service.ISysRoleService;
import com.eii.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 角色信息
 */
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController {

    private final static String CONTROLLER_TITLE = "角色管理";

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @RequiresPermissions("system:role:list")
    @GetMapping("/list")
    public PageResult list(SysRole role) {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getPageResult(list);
    }

    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.EXPORT)
    @RequiresPermissions("system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role) throws IOException {
        List<SysRole> list = roleService.selectRoleList(role);
        List<SysRoleExcel> sysRoleExcels = BeanUtil.copyToList(list, SysRoleExcel.class);
        String datestr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String filename = "角色数据" + datestr + ".xlsx";
        ExcelUtils.exportExcelStream(response, filename, SysRoleExcel.class, sysRoleExcels);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @RequiresPermissions("system:role:query")
    @GetMapping(value = "/{roleId}")
    public Result getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return Result.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @RequiresPermissions("system:role:add")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return Result.fail("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return Result.fail("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toResult(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping
    public Result edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return Result.fail("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return Result.fail("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toResult(roleService.updateRole(role));
    }

    /**
     * 修改保存数据权限
     */
    @RequiresPermissions("system:role:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping("/dataScope")
    public Result dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return toResult(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:role:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(SecurityUtils.getUsername());
        return toResult(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @RequiresPermissions("system:role:remove")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.DELETE)
    @DeleteMapping("/{roleIds}")
    public Result remove(@PathVariable Long[] roleIds) {
        return toResult(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @RequiresPermissions("system:role:query")
    @GetMapping("/optionselect")
    public Result optionselect() {
        return Result.success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/allocatedList")
    public PageResult allocatedList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectAllocatedList(user);
        return getPageResult(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/unallocatedList")
    public PageResult unallocatedList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList(user);
        return getPageResult(list);
    }

    /**
     * 取消授权用户
     */
    @RequiresPermissions("system:role:edit")
    @AuditLog(title = "角色管理", operation = BusinessTypeConstants.GRANT)
    @PutMapping("/authUser/cancel")
    public Result cancelAuthUser(@RequestBody SysUserRole userRole) {
        return toResult(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @RequiresPermissions("system:role:edit")
    @AuditLog(title = "角色管理", operation = BusinessTypeConstants.GRANT)
    @PutMapping("/authUser/cancelAll")
    public Result cancelAuthUserAll(Long roleId, Long[] userIds) {
        return toResult(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @RequiresPermissions("system:role:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.GRANT)
    @PutMapping("/authUser/selectAll")
    public Result selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return toResult(roleService.insertAuthUsers(roleId, userIds));
    }
}
